<template>
  <el-card>
    <el-form :inline="true" class="form">
      <el-form-item label="职位搜索">
        <el-input
          placeholder="请输入搜索职位关键字"
          size="normal"
          clearable
          @change=""
          v-model="roleName"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="default"
          @click="search"
          :disabled="roleName ? false : true"
          >搜索</el-button
        >
        <el-button type="primary" size="default" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0px">
    <el-button type="primary" size="default" @click="addRole" icon="plus"
      >添加职位</el-button
    >
    <el-table border style="margin: 10px 0px" :data="RoleListArr">
      <el-table-column type="index" align="center" label="#"></el-table-column>
      <el-table-column label="id" align="center" prop="id"></el-table-column>
      <el-table-column
        label="职位名称"
        align="center"
        show-overflow-tooltip
        prop="roleName"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        show-overflow-tooltip
        prop="createTime"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        show-overflow-tooltip
        prop="updateTime"
      ></el-table-column>
      <el-table-column label="操作" width="280px" align="center">
        <template #="{ row}">
          <el-button
            type="primary"
            size="small"
            @click="setPermisstion(row)"
            icon="UserFilled"
            >分配权限</el-button
          >
          <el-button type="primary" size="small" @click="updataRole(row)" icon="edit"
            >编辑</el-button
          >
          <el-popconfirm :title="`你确定删除${row.roleName}角色？`" @confirm="deleteRole(row.id)">
            <template #reference>
              <el-button type="primary" size="small" @click="" icon="delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize4"
      :page-sizes="[10, 20, 30, 40]"
      :background="true"
      layout=" prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @current-change="getHasRole(pageNo)"
      @size-change="getHasRole()"
    />
    <el-dialog
      v-model="showDialog"
      :title="RoleParams.id ? '修改角色' : '添加角色'"
      width="600"
    >
      <el-form :model="RoleParams" :rules="rules" ref="form">
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            placeholder="请填写角色名称"
            size="normal"
            clearable
            @change=""
            v-model="RoleParams.roleName"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="saveAddRole"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
  <!-- 抽屉组件 -->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>分配菜单与按钮权限</h4>
    </template>
    <template #default>
      <!-- 树形控件 -->
      <!-- data:展示数据
            show-checkbox：复选框
            node-key="id" 节点唯一表示 
            :default-expanded-keys：默认展开节点的数据（id做表示）
            :default-checked-keys ：默认勾选节点数据
            :props="defaultProps"：配置选项{children：子节点，label：展示名字}
            default-expand-all：是否展示所有节点-->
      <el-tree
        style="max-width: 600px"
        :data="MenuArr"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="MenuIdArr"
        :props="defaultProps"
        ref="tree"
      />
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="handler">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
import {
  reqAllMenuList,
  reqAllRoleList,
  reqDeleteRole,
  reqSetPermisstion,
  reqUpdataAndAddRole,
} from "@/api/acl/role";
import {
  MenuList,
  MenuResponseData,
  Records,
  RoleData,
  RoleDataList,
} from "@/api/acl/role/type";
import useLayOutSettingStore from "@/store/modules/setting";
import { ElMessage } from "element-plus";
let pageNo = ref<number>(1);
//一页展示多少条数据
let pageSize4 = ref<number>(10);
//查询关键字
let roleName = ref<string>("");
//获取所有角色数组
let RoleListArr = ref<Records>([]);
//总数据
let total = ref<number | string>("");
//获取仓库
let useStore = useLayOutSettingStore();
//显示dialog
let showDialog = ref<boolean>(false);
//角色数据格式
let RoleParams = reactive<RoleData>({
  id: "",
  createTime: "",
  updateTime: "",
  roleName: "",
  remark: null,
});
//获取form组件实例
let form = ref<any>();
//控制抽屉显示与隐藏
let drawer = ref<boolean>(false);
//存储权限数组
let MenuArr = ref<MenuList>([]);
//准备数组：用于勾选结点的ID（四级ID）
let MenuIdArr = ref<any>([]);
//获取树形控件的组件实例

let tree = ref<any>();
//分配权限按钮回调
const setPermisstion = async (row: RoleData) => {
  drawer.value = true;
  ////收集当前数据
  Object.assign(RoleParams, row);
  let result: MenuResponseData = await reqAllMenuList(RoleParams.id as number);
  if (result.code == 200) {
    Object.assign(MenuArr.value, result.data);
    //递归
    MenuIdArr.value = filterSelectArr(MenuArr.value, []);
  }
};
//抽屉确定按钮回调
const handler = async () => {
  //职位ID
  const roleId = RoleParams.id;
  let arr = tree.value.getCheckedKeys();
  //半选
  let arr1 = tree.value.getHalfCheckedKeys();
  //下发权限
  let permisstionId = arr.concat(arr1);
  let result = await reqSetPermisstion(roleId as number, permisstionId);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: "角色权限分配成功",
    });
    drawer.value = false;
    //页面刷新
    window.location.reload();
  } else {
    ElMessage({
      type: "error",
      message: "角色权限分配失败",
    });
    drawer.value = false;
    //刷新用于重新获取权限
    window.location.reload();
  }
};
//递归方法(只需要考虑四级)
const filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level == 4) {
      initArr.push(item.id);
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr);
    }
  });
  return initArr;
};
//树形控件配置选项
const defaultProps = {
  children: "children",
  label: "name",
};
//封装获取方法
const getHasRole = async (pager = 1) => {
  pageNo.value = pager;
  let result: RoleDataList = await reqAllRoleList(
    pageNo.value,
    pageSize4.value,
    roleName.value
  );
  RoleListArr.value = result.data.records;
  total.value = result.data.total;
};
//搜索按钮
const search = () => {
  getHasRole();
  roleName.value = "";
};
//重置按钮
const reset = () => {
  useStore.refsh = !useStore.refsh;
};
//添加角色
const addRole = () => {
  showDialog.value = true;
  //清楚校验字段
  nextTick(() => {
    form.value.clearValidate("");
    Object.assign(RoleParams, {
      id: "",
      createTime: "",
      updateTime: "",
      roleName: "",
      remark: null,
    });
  });
};
//添加提交按钮
const saveAddRole = async () => {
  await form.value.validate();
  let result = await reqUpdataAndAddRole(RoleParams);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: RoleParams.id ? "更新成功" : "添加成功",
    });
    getHasRole(RoleParams.id ? pageNo.value : 1);
    showDialog.value = false;
  } else {
    ElMessage({
      type: "error",
      message: RoleParams.id ? "更新失败" : "添加失败",
    });
    showDialog.value = false;
  }
};
const validatorRoleName = (_rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    if (
      RoleListArr.value.find((element) => element.roleName === RoleParams.roleName) &&
      RoleParams.id == ""
    ) {
      callBack(new Error("职位名称重复"));
    } else {
      callBack();
    }
  } else {
    callBack(new Error("职位名称至少两位"));
  }
};
//表单校验规则
const rules = {
  roleName: [
    {
      required: true,
      trigger: "blur",
      validator: validatorRoleName,
    },
  ],
};
//取消按钮
const cancel = () => {
  showDialog.value = false;
};
//更新按钮
const updataRole = (row: RoleData) => {
  showDialog.value = true;
  Object.assign(RoleParams, row);
  nextTick(() => {
    form.value.clearValidate("");
  });
};
//删除角色按钮
const deleteRole = async(id:number)=>{
  let result:any =  await reqDeleteRole(id)
  if(result.code==200){
    ElMessage({
      type:'success',
      message:'删除角色成功'
    })
    getHasRole(RoleListArr.value.length>1?pageNo.value:pageNo.value-1)
  }
}
onMounted(() => {
  getHasRole();
});
</script>

<style scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
}
</style>
